package com.qitianyong.selfclass;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


/**
 * Created by gy on 2017/4/5.
 */

public class GKUSBCmdList {
    public List<CommandMessage> __cmdList = new ArrayList<>(); // 指令信息列表
    private Lock __lock = new ReentrantLock();  // 指令发送互斥锁

    public void addCommand(int command, Object message) {
        __lock.lock();
        __cmdList.add(new CommandMessage(command, message));
        __lock.unlock();
    }

    public void addCommandNoRepeated(int command, List messages) {
        if (messages == null) {
            return;
        }
        List<CommandMessage> msgs = new ArrayList<>(messages.size());
        for (int i = 0; i < messages.size(); i++) {
            CommandMessage commandMessage = new CommandMessage(command, messages.get(i));
            if(__cmdList.contains(commandMessage)){
                continue;
            }
            msgs.add(commandMessage);
        }
        __lock.lock();
        __cmdList.addAll(msgs);
        __lock.unlock();
    }

    public void addToFirstNoRepeated(int command, Object message) {
        CommandMessage msg = new CommandMessage();
        msg.command = command;
        msg.message = message;
        __lock.lock();
        __cmdList.remove(msg);
        __cmdList.add(0, msg);
        __lock.unlock();
    }

    public CommandMessage popFirstCmd() {
        if (__cmdList.size() == 0) {
            return null;
        }
        __lock.lock();
        CommandMessage remove = __cmdList.remove(0);
        __lock.unlock();
        return remove;
    }

    public void clearSpeciallyTypeCommand(int type) {
        __lock.lock();
        Iterator<CommandMessage> iterator = __cmdList.iterator();
        while (iterator.hasNext()) {
            CommandMessage next = iterator.next();
            if (next.command == type) {
                iterator.remove();
            }
        }
        __lock.unlock();
    }
    public void clear() {
        __lock.lock();
        __cmdList.clear();
        __lock.unlock();
    }
}
